package com.ff.javamonkey.ui;

import java.io.File;
import java.io.IOException;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;

import com.ff.javamonkey.R;
import com.ff.javamonkey.socket.ClientConnect;
import com.ff.javamonkey.socket.XSocketConnect;
import com.ff.javamonkey.sqlite.type.Acrlac;

public class SendToDevicesActivity extends ListActivity {
	// Debugging
	private static final String TAG = "SendToDevicesActivity";
	
	private Acrlac acrlac;
	
	// For intent
	public static final String ACRLAC_PARCELABLE = "AcrlacParcelable";
	
	public SendToDevicesActivity() {
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.browse_devices);
		acrlac = new Acrlac();
		
		// There's a parcel coming.
		if (getIntent().getExtras()!=null) {
			if (getIntent().getExtras().containsKey(ACRLAC_PARCELABLE)) {
				acrlac = (Acrlac)getIntent().getExtras().getParcelable(ACRLAC_PARCELABLE);
				if (acrlac != null) {
					new SendToDevicesTask().execute();
				}
			}
		}
	}
	
	private class SendToDevicesTask extends AsyncTask<Void, Void, Integer> {

		ClientConnect connect;
		
		@Override
		protected void onPreExecute() {
			connect = new XSocketConnect();
		}
		
		@Override
		protected Integer doInBackground(Void... params) {
			// Read local files.
    		File dir = new File(Environment.getExternalStorageDirectory(), "data");
    		if (!dir.exists()) if(!dir.mkdir()) return -1; // Failed to make a directory.
    		File fileOut = new File(Environment.getExternalStorageDirectory(), "data/"+
    				acrlac.getmFilename());
    		if (fileOut.exists()) { // yay, we got files
    			try {
					connect.connect("", "");
				} catch (IOException e) {
					e.printStackTrace();
				}
    			connect.write(fileOut);
    		}
			return -1;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			
		}
	}
	
}
